package com.colbby.datahouse.database;

import java.sql.Connection;
import java.util.Objects;

import com.colbby.datahouse.db.DBAccesser;
import com.colbby.datahouse.db.SqlObject;
import com.colbby.datahouse.entity.Member;
import com.colbby.datahouse.lock.Lock;
import com.colbby.datahouse.lock.LockFactory;
import com.colbby.datahouse.message.ConnectionUtils;

public class MemberInserter extends AbstractInserter<Member> {

	private static final Lock<String> lock = LockFactory.fac();
	
	@Override
	protected Member findFromDatabase(Member member) {
		Connection conn = ConnectionUtils.getConnection();
		DBAccesser db = new DBAccesser(conn);
		Member condition = new Member();
		condition.setNick(member.getNick());
		condition.setShopNick(member.getShopNick());
		return db.selectOne(Member.class, condition);
	}

	@Override
	protected void insertInto(Member member) {
		Connection conn = ConnectionUtils.getConnection();
		DBAccesser db = new DBAccesser(conn);
		db.save(member);
	}

	@Override
	protected void update(Member newOne, Member oldOne) {
		if(newOne.getModified().getTime() <= oldOne.getModified().getTime()) {
			return;
		}
		Member updated = new Member();
		updated.setModified(newOne.getModified());
		if(!Objects.equals(newOne.getAddress(), oldOne.getAddress())) {
			updated.setAddress(newOne.getAddress());
		}
		if(!Objects.equals(newOne.getCity(), oldOne.getAddress())) {
			updated.setCity(newOne.getCity());
		}
		if(!Objects.equals(newOne.getDistrict(), oldOne.getDistrict())) {
			updated.setDistrict(newOne.getDistrict());
		}
		if(!Objects.equals(newOne.getLastTradeTime(), oldOne.getLastTradeTime())) {
			updated.setLastTradeTime(newOne.getLastTradeTime());
		}
		if(!Objects.equals(newOne.getMobile(), oldOne.getMobile())) {
			updated.setMobile(newOne.getMobile());
		}
		if(!Objects.equals(newOne.getName(), oldOne.getName())) {
			updated.setName(newOne.getName());
		}
		if(!Objects.equals(newOne.getPhone(), oldOne.getPhone())) {
			updated.setPhone(newOne.getPhone());
		}
		if(!Objects.equals(newOne.getState(), oldOne.getState())) {
			updated.setState(newOne.getState());
		}
		Connection conn = ConnectionUtils.getConnection();
		DBAccesser db = new DBAccesser(conn);
		Member condition = new Member();
		condition.setNick(oldOne.getNick());
		condition.setShopNick(oldOne.getShopNick());
		db.update(updated, condition);
	}

	@Override
	protected void lock(Member member) {
		lock.lock(member.getNick());
	}

	@Override
	protected void unlock(Member member) {
		lock.unlock(member.getNick());
	}

}